# how to dump list into json?
# json.dumps(list)
import json  
from nekoTrace.nekonekotrace.models import *
from nekoTrace.nekonekotrace.logic import RenrenAPI



def userGenerator(userId):
    userId = OpenUser.objects.get(id = userId)
    jsonStr = "{"
    jsonStr += "\"id\":" + str(userId.id)
    jsonStr += ",\"Name\":\"" + userId.Name + "\""
    jsonStr += "}"
    return jsonStr


def catInfoGenerator(catInfo):
    catInfo = CatInfo.objects.get(id = catInfo)
    jsonStr = "{"
    jsonStr += "\"CurLocation\":" + str(catInfo.CurLocation_id)
    jsonStr += ",\"Portrait\":\"" + catInfo.Portrait + "\""
    jsonStr += ",\"Name\":\"" + catInfo.Name + "\""
    jsonStr += ",\"Sex\":" + str(catInfo.Sex)
    jsonStr += "}"
    return jsonStr

def catInfoAllGenerator():
    jsonStr = "["
    count = 0
    for ci in (CatInfo.objects.all()):
        if (count != 0):
            jsonStr += ","
        jsonStr += catInfoGenerator(ci.id)
        count += 1
    jsonStr += "]"
    return jsonStr
        

def locationInfoGenerator(lInfo):
    lInfo = LocationInfo.objects.get(id = lInfo)
    jsonStr = "{"
    jsonStr += "\"Time\":\"" + lInfo.Time.strftime('%Y-%m-%d %H:%M:%S') + "\""
    jsonStr += ",\"Location\":" + locationByID(lInfo.LocationID.id)
    jsonStr += ",\"Cat\":" + str(lInfo.CatID.id)
    jsonStr += "}"
    return jsonStr

def locationInfoByCatGenerator(catid):
    jsonStr = "["
    count = 0
    for lInfo in LocationInfo.objects.filter(CatID = catid).order_by("-id"):
        if (count != 0):
            jsonStr += ","
        jsonStr += locationInfoGenerator(lInfo.id)
        count += 1
    jsonStr += "]"
    return jsonStr

def locationInfoAllGenerator():
    jsonStr = "["
    count = 0
    for lInfo in LocationInfo.objects.all().order_by("-id"):
        if (count != 0):
            jsonStr += ","
        jsonStr += locationInfoGenerator(lInfo.id)
        count += 1
    jsonStr += "]"
    return jsonStr

def catImpressionByCatGenerator(catId):
    jsonStr = "["
    catId = CatInfo.objects.get(id = catId)
    first = True
    for catimp in (CatImpression.objects.all().filter(CatID = catId).order_by("-id")):
        if first:
            first = False 
        else:
            jsonStr += ","
        jsonStr += "{"
        jsonStr += "\"Cat\":" + str(catId.id)
        jsonStr += ",\"Author\":" + userGenerator(catimp.UserID.id)
        jsonStr += ",\"Content\":\"" + catimp.Content + "\""
        jsonStr += ",\"Time\":\"" + catimp.Time.strftime('%Y-%m-%d %H:%M:%S') + "\""
        jsonStr +="}"
    jsonStr += "]"
    return jsonStr

def catImpressionByUserGenerator(userId):
    userId = OpenUser.objects.get(id = userId)
    jsonStr = "["
    first = True
    for catimp in (CatImpression.objects.all().filter(UserID = userId).order_by("-id")):
        if first:
            first = False 
        else:
            jsonStr += ","
        jsonStr += "{"
        jsonStr += "\"Cat\":" + str(catimp.CatID.id)
        jsonStr += ",\"Author\":" + userGenerator(userId.id)
        jsonStr += ",\"Content\":\"" + catimp.Content + "\""
        jsonStr += ",\"Time\":\"" + catimp.Time.strftime('%Y-%m-%d %H:%M:%S') + "\""
        jsonStr +="}"
    jsonStr += "]"
    return jsonStr

def catAlbumByCatGenerator(catId):
    jsonStr = "["
    catId = CatInfo.objects.get(id = catId)
    first = True
    for catalb in (Album.objects.all().filter(CatID = catId).order_by("-id")):
        if first:
            first = False 
        else:
            jsonStr += ","
        jsonStr += "{"
        jsonStr += "\"Cat\":" + str(catId.id)
        jsonStr += ",\"Author\":" + userGenerator(catalb.Author.id)
        jsonStr += ",\"URL\":\"" + catalb.URL + "\""
        jsonStr += ",\"Time\":\"" + catalb.Time.strftime('%Y-%m-%d %H:%M:%S') + "\""
        jsonStr +="}"
    jsonStr += "]"
    return jsonStr

def catAlbumByUserGenerator(userId):
    jsonStr = "["
    userId = OpenUser.objects.get(id = userId)
    first = True
    for catalb in (Album.objects.all().filter(Author = userId).order_by("-id")):
        if first:
            first = False 
        else:
            jsonStr += ","
        jsonStr += "{"
        jsonStr += "\"Cat\":" + str(catalb.CatID.id)
        jsonStr += ",\"Author\":" + userGenerator(userId.id)
        jsonStr += ",\"URL\":\"" + catalb.URL + "\""
        jsonStr += ",\"Time\":\"" + catalb.Time.strftime('%Y-%m-%d %H:%M:%S') + "\""
        jsonStr +="}"
    jsonStr += "]"
    return jsonStr

def catAlbumByIDGenerator(userId):
    jsonStr = "{"
    userId = Album.objects.get(id = userId)
    jsonStr += "\"id\":" + str(userId.id)
    jsonStr += ",\"Cat\":" + str(userId.CatID.id)
    jsonStr += ",\"Author\":" + userGenerator(userId.Author.id)
    jsonStr += ",\"URL\":\"" + userId.URL + "\""
    jsonStr += ",\"Time\":\"" + userId.Time.strftime('%Y-%m-%d %H:%M:%S') + "\""
    jsonStr += "}"
    return jsonStr

def catImpressionByIDGenerator(userId):
    jsonStr = "{"
    userId = CatImpression.objects.get(id = userId)
    jsonStr += "\"id\":" + str(userId.id)
    jsonStr += ",\"Cat\":" + str(userId.CatID.id)
    jsonStr += ",\"Author\":" + userGenerator(userId.UserID.id)
    jsonStr += ",\"Time\":\"" + userId.Time.strftime('%Y-%m-%d %H:%M:%S') + "\""
    jsonStr += ",\"Content\":\"" + userId.Content + "\""
    jsonStr += "}"
    return jsonStr

def catTreatByCatGenerator(catId):
    jsonStr = "["
    catId = CatInfo.objects.get(id = catId)
    first = True
    for catalb in (Treat.objects.all().filter(CatID = catId).order_by("-id")):
        if first:
            first = False 
        else:
            jsonStr += ","
        jsonStr += "{"
        jsonStr += "\"Cat\":" + str(catId.id)
        jsonStr += ",\"Author\":" + userGenerator(catalb.Author.id)
        jsonStr += ",\"Time\":\"" + catalb.Time.strftime('%Y-%m-%d %H:%M:%S') + "\""
        jsonStr +="}"
    jsonStr += "]"
    return jsonStr

def catTreatByUserGenerator(userId):
    jsonStr = "["
    userId = OpenUser.objects.get(id = userId)
    first = True
    for catalb in (Treat.objects.all().filter(Author = userId).order_by("-id")):
        if first:
            first = False 
        else:
            jsonStr += ","
        jsonStr += "{"
        jsonStr += "\"Cat\":" + str(catalb.CatID.id)
        jsonStr += ",\"Author\":" + userGenerator(userId.id)
        jsonStr += ",\"Time\":\"" + catalb.Time.strftime('%Y-%m-%d %H:%M:%S') + "\""
        jsonStr +="}"
    jsonStr += "]"
    return jsonStr

def catTreatByIDGenerator(Id):
    jsonStr = "{"
    userId = Treat.objects.get(id = Id)
    jsonStr += "\"Cat\":" + str(userId.CatID.id)
    jsonStr += ",\"Author\":" + userGenerator(userId.Author.id)
    jsonStr += ",\"Time\":\"" + userId.Time.strftime('%Y-%m-%d %H:%M:%S') + "\""
    jsonStr += "}"
    return jsonStr

def sayingByCatGenerator(catId):
    jsonStr = "["
    catId = CatInfo.objects.get(id = catId)
    first = True
    for catalb in (Saying.objects.all().filter(CatID = catId).order_by("-id")):
        if first:
            first = False 
        else:
            jsonStr += ","
        jsonStr += "{"
        jsonStr += "\"Cat\":" + str(catId.id)
        jsonStr += ",\"Content\":\"" + catalb.Content + "\""
        jsonStr += ",\"Time\":\"" + catalb.Time.strftime('%Y-%m-%d %H:%M:%S') + "\""
        jsonStr +="}"
    jsonStr += "]"
    return jsonStr

def sayingByIDGenerator(Id):
    jsonStr = "{"
    userId = Saying.objects.get(id = Id)
    jsonStr += "\"Cat\":" + str(userId.CatID.id)
    jsonStr += ",\"Content\":\"" + userId.Content + "\""
    jsonStr += ",\"Time\":\"" + userId.Time.strftime('%Y-%m-%d %H:%M:%S') + "\""
    jsonStr += "}"
    return jsonStr


def newsByIDGenerator(nId):
    nId = CatStatus.objects.get(id = nId)
    jsonStr = "{"
    jsonStr += "\"_type\":" + str(nId.Type)
    #0 for location
    #1 for treat   2 for photo update    3 for say something
    if (nId.Type == 0):
        jsonStr += ",\"Content\":" + locationInfoGenerator(nId.TargetID)
    elif (nId.Type == 1):
        jsonStr += ",\"Content\":" + catTreatByIDGenerator(nId.TargetID)
    elif (nId.Type == 2):
        jsonStr += ",\"Content\":" + catAlbumByIDGenerator(nId.TargetID)
    elif (nId.Type == 3):
        jsonStr += ",\"Content\":" + sayingByIDGenerator(nId.TargetID)
    elif (nId.Type == 4):
        jsonStr += ",\"Content\":" + catImpressionByIDGenerator(nId.TargetID)    
    
    jsonStr += ",\"Cat\":" + str(nId.CatID.id)
    jsonStr += "}"
    return jsonStr

def newslistByCatGenerator(catid):
    catid = CatInfo.objects.get(id = catid)
    count = 0
    jsonStr = "["
    for cs in (CatStatus.objects.filter(CatID = catid).order_by("-id")):
        if (count == 10):
            break
        if (count == 0):
            pass
        else:
            jsonStr += ","
        jsonStr += newsByIDGenerator(cs.id)
        #jsonStr += "}"
        count += 1
    jsonStr += "]"
    return jsonStr

def newslistAllGenerator():
    catid = CatInfo.objects.all()
    count = 0
    jsonStr = "["
    for cs in (CatStatus.objects.all().order_by("-id")):
        if (count == 10):
            break
        if (count != 0):
            jsonStr += ","
        jsonStr += newsByIDGenerator(cs.id)
        #jsonStr += "}"
        count += 1
    jsonStr += "]"
    return jsonStr

def catAlbumListGenerator():
    count = 0
    jsonStr = "["
    for cs in (Album.objects.all().order_by("-id")):
        if (count == 0):
            pass
        else:
            jsonStr += ","
        jsonStr += catAlbumByIDGenerator(cs.id)
        #jsonStr += "}"
        count += 1
    jsonStr += "]"
    return jsonStr
    
def catTreatAllGenerator():
    count = 0
    jsonStr = "["
    for cs in (Treat.objects.all().order_by("-id")):
        if (count == 0):
            pass
        else:
            jsonStr += ","
        jsonStr += catTreatByIDGenerator(cs.id)
        #jsonStr += "}"
        count += 1
    jsonStr += "]"
    return jsonStr

def catImpressionAllGenerator():
    count = 0
    jsonStr = "["
    for cs in (CatImpression.objects.all().order_by("-id")):
        if (count == 0):
            pass
        else:
            jsonStr += ","
        jsonStr += catImpressionByIDGenerator(cs.id)
        #jsonStr += "}"
        count += 1
    jsonStr += "]"
    return jsonStr

def newslistSinceByCatGenerator(time, catid):
    catid = CatInfo.objects.get(id = catid)
    tstr = time.strftime('%Y-%m-%d %H:%M:%S')
    jsonStr = "["
    count = 0
    for cs in (CatStatus.objects.filter(CatID = catid).order_by("-id")):
        if (cs.Type == 0):
            ttstr = LocationInfo.objects.get(id = cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        elif (cs.Type == 1):
            ttstr = Treat.objects.get(id = cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        elif (cs.Type == 2):
            ttstr = Album.objects.get(id = cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        elif (cs.Type == 3):
            ttstr = Saying.objects.get(id = cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        elif (cs.Type == 4):
            ttstr = CatImpression.objects.get(id = cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        
        if (tstr < ttstr):
            if (count == 0):
                pass
            else:
                jsonStr += ","
            jsonStr += newsByIDGenerator(cs.id)
            #jsonStr += "}"
            count += 1
        else:
            break
    jsonStr += "]"
    return jsonStr

def newslistSinceAllGenerator(time):
    tstr = time.strftime('%Y-%m-%d %H:%M:%S')
    jsonStr = "["
    count = 0
    for cs in (CatStatus.objects.all().order_by("-id")):
        if (cs.Type == 0):
            ttstr = LocationInfo.objects.get(id = cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        elif (cs.Type == 1):
            ttstr = Treat.objects.get(id = cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        elif (cs.Type == 2):
            ttstr = Album.objects.get(id = cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        elif (cs.Type == 3):
            ttstr = Saying.objects.get(id = cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        elif (cs.Type == 4):
            ttstr = CatImpression.objects.get(id = cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
            
        if (tstr < ttstr):
            if (count == 0):
                pass
            else:
                jsonStr += ","
            jsonStr += newsByIDGenerator(cs.id)
            
            #jsonStr += "}"
            count += 1
        #else:
        #    break
    jsonStr += "]"
    return jsonStr

def locationList():
    jsonStr = "["
    first = True
    for cs in (Location.objects.all()):
        if first:
            first = False 
        else:
            jsonStr += ","
        jsonStr += "{"
        jsonStr += "\"id\":" + str(cs.id)
        jsonStr += ",\"Name\":\"" + cs.Name + "\""
        jsonStr += ",\"X\":\"" + str(cs.x) + "\""
        jsonStr += ",\"Y\":\"" + str(cs.y) + "\""
        jsonStr +="}"
    jsonStr += "]"
    return jsonStr

def locationByID(lid):
    
    cs = Location.objects.get(id = lid)
        
    jsonStr = "{"
    jsonStr += "\"id\":" + str(cs.id)
    jsonStr += ",\"Name\":\"" + cs.Name + "\""
    jsonStr += ",\"X\":\"" + str(cs.x) + "\""
    jsonStr += ",\"Y\":\"" + str(cs.y) + "\""
    jsonStr += "}"
    return jsonStr

# get user info by RenRenId
# must send apiClient as a param
def userInfo(rrId, apiClient):
    target = OpenUser.objects.get(id = rrId)
    
    """
        show the user Name
        Photo
        And statistics
            photo uploaded
            impression uploaded
            
            favorite pets(will get those pets news)
    """
    params = {"method": "users.getInfo", "fields": "name,headurl,tinyurl", "uids":str(rrId)}
    response = (apiClient.request(params))
    #response is a list, dict struct
    
    # now add statistics
    #photo
    response[0][u'photoNum'] = Album.objects.filter(Author_id = rrId).count()
    #impression
    response[0][u'impressionNum'] = CatImpression.objects.filter(UserID_id = rrId).count()
    
    catlist = []
    for ca in Favorite.objects.filter(UserID_id = rrId):
        catlist.append(ca.CatID_id)
    
    response[0][u'favoriteCat'] = catlist
    
    return json.dumps(response[0])

# get a cat's follower
# given the catid, return the id of the followers 
def catfollower(catid):
    ret = [] #a new list
    for ca in Favorite.objects.filter(CatID_id = catid):
        ret.append(ca.UserID_id)
    return json.dumps(ret)
    
    
    
    